﻿/*** MikeWare Framework ************************************
* This class is part of product of MikeWare.Framework.
* 
* Author      : Mike Cheers
* Mail        : mikecheers@126.com
* Create Date : 2018/9/18
* Summary     : 
* 
* 
* Modified By : 
* Date        : 
* Mail        : 
* Comment     : 
**************************************************************/

namespace MikeWare.Core.WinApiWrappers
{
    using System;
    using System.Runtime.InteropServices;

    internal static class Kernel32APIWrapper
    {
        [DllImport("Kernel32.dll", EntryPoint = "GetLastError")]
        public extern static int GetLastError();

        [DllImport("Kernel32.dll", EntryPoint = "FormatMessage")]
        public extern static Int32 FormatMessage(Int32 dwFlags, IntPtr lpSource, Int32 dwMessageId, UInt16 dwLanguageId, ref IntPtr lpBuffer, Int32 nSize, IntPtr arguments);

        public static string GetWin32ErrorMessage(int errorcode)
        {
            string message = string.Empty;
            IntPtr lpBuffer = IntPtr.Zero;
            if (0 != FormatMessage(FormatMessageParams.FORMAT_MESSAGE_ALLOCATE_BUFFER
                | FormatMessageParams.FORMAT_MESSAGE_FROM_SYSTEM
                | FormatMessageParams.FORMAT_MESSAGE_IGNORE_INSERTS
                , IntPtr.Zero, errorcode, 0, ref lpBuffer, 0, IntPtr.Zero))
            {
                message
                    = Marshal.PtrToStringAnsi(lpBuffer).TrimEnd(Environment.NewLine.ToCharArray());
                Marshal.FreeHGlobal(lpBuffer);
            }

            return message;
        }

        public class FormatMessageParams
        {
            public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
            public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
            public const int FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
            public const int FORMAT_MESSAGE_FROM_STRING = 0x00000400;
            public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
            public const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
        }

        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
    }
}
